//
//  ViewController.m
//  cjyebh5
//
//  Created by lt on 2017/5/25.
//  Copyright © 2017年 lt. All rights reserved.
//

#import "ViewController.h"
#import "MBProgressHUD.h"
#import "LoadFailureView.h"
#import "AppUtil.h"
#import "MenuView.h"

@interface ViewController ()<MBProgressHUDDelegate>
{
    UIWebView *webView;
    MBProgressHUD* hud;
    LoadFailureView* errorView;
    //UIToolbar * bottomView ;
    MenuView* menuView;
    BOOL isShow;
    BOOL isReload;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //self.url=@"http://www.xiongmaoleyuan.vip/index.php/Home/Regus/login.html";
    //self.url=@"http://www.bidcoin.vip/";
    self.url=@"http://www.renshenlianzhuangyuan.com/";

    self.edgesForExtendedLayout = UIRectEdgeNone;
    webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,self.view.frame.size.width,[UIScreen mainScreen].bounds.size.height)];
    webView.backgroundColor=[UIColor whiteColor];
    [webView setMediaPlaybackRequiresUserAction:NO];
    webView.delegate=self;
    isShow=true;
    [self.view addSubview: webView];
    menuView=[[MenuView alloc]initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width-180)/2,self.view.frame.size.height-60 , 180, 60)];
    //menuView.backgroundColor=[UIColor redColor];
    [self.view addSubview:menuView];
    [menuView.previousBtn addTarget:self action:@selector(previous) forControlEvents:UIControlEventTouchUpInside];
    [menuView.nextBtn addTarget:self action:@selector(forward) forControlEvents:UIControlEventTouchUpInside];
    [menuView.refreshBtn addTarget:self action:@selector(refresh) forControlEvents:UIControlEventTouchUpInside];
    UITapGestureRecognizer* singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menu)];
    singleRecognizer.numberOfTapsRequired = 1; // 单击
    singleRecognizer.delegate = self;
    singleRecognizer.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:singleRecognizer];
    isReload=true;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}
-(NSArray*) setBottomTools{
    NSMutableArray* array=[NSMutableArray array];
    NSArray* arrImgs=@[@"previous.png",@"forward.png",@"refresh.png",@"browser.png"];
    UITapGestureRecognizer*previousTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(previous)];
    UITapGestureRecognizer*forwardTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(forward)];
    UITapGestureRecognizer*refreshTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(refresh)];
    UITapGestureRecognizer*browserTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(browser)];
    NSArray* arrActions=[NSArray arrayWithObjects:previousTap,forwardTap,refreshTap,browserTap,nil];
    for(int i=0;i<arrImgs.count;i++){
        UIImageView* iv=[[UIImageView alloc] initWithFrame:CGRectMake(0,0,25,25)];
        UIImage* img=[UIImage imageNamed:arrImgs[i]];
        [iv setImage:img];
        if(i==0)
            [iv setHighlightedImage:[UIImage imageNamed:@"previous_selected.png"]];
        else if(i==1)
            [iv setHighlightedImage:[UIImage imageNamed:@"forward_selected.png"]];
        iv.userInteractionEnabled=true;
        [iv addGestureRecognizer:arrActions[i]];
        UIBarButtonItem* btn=[[UIBarButtonItem alloc] initWithCustomView:iv];
        [array addObject:btn];
        if(i!=arrImgs.count-1){
            UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
            [array addObject:btnSpace];
        }
    }
    return [array copy];
}

-(void) previous{
    // NSLog(@"previous");
    if(webView.canGoBack){
        [webView goBack];
        if(errorView)
            [errorView removeFromSuperview];
    }
}

-(void) forward{
    //  NSLog(@"forward");
    if(webView.canGoForward){
        [webView goForward];
        if(errorView)
            [errorView removeFromSuperview];
    }
}

-(void) refresh{
    //  NSLog(@"refresh");
    [webView reload];
    if(errorView)
        [errorView removeFromSuperview];
}

-(void) browser{
    // NSLog(@"browser");
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.url]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.hidden = YES;
    //self.tabBarController.tabBar.hidden=YES;
    //self.navigationController.navigationBarHidden = NO;
    //self.navigationController.navigationBar.hidden = NO;
    //self.navigationController.navigationBar.barTintColor=[UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1];
    //self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:253.0/255.0 green:98.0/255.0 blue:11.0/255.0 alpha:1];
    //if(self.navigationController.navigationBar.hidden)
    //    self.navigationController.navigationBar.hidden = NO;
    //[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    //NSLog(@"webview_url=%@",self.url);
    NSURL *url = [NSURL URLWithString:self.url];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    webView.scalesPageToFit = YES;
    webView.opaque=NO;
    [webView loadRequest:request];
}

-(void)dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion
{
    if ( self.presentedViewController)
    {
        [super dismissViewControllerAnimated:flag completion:completion];
    }
}


//- (void)presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion {
//    [super presentViewController:viewControllerToPresent animated:flag completion:completion];
//}

-(void)webViewDidStartLoad:(UIWebView *)webView
{
    NSLog(@"webViewDidStartLoad");
    //开始加载网页调用此方法
    if(!hud){
        hud=[[MBProgressHUD alloc]initWithView:self.view];
        hud.delegate=self;
        [AppUtil showProgressDialog:hud withContent:@"正在加载"];
        [self.view addSubview:hud];
    }
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    //获得请求的URL,第一次是路径，当在web上点击按钮后获得的是web穿过来的路径。
    NSString *requestString = [[request URL] absoluteString];
    //根据":"拆分字符串，返回数组。
    NSArray *components = [requestString componentsSeparatedByString:@":"];
    NSLog(@"requestString==%@",requestString);
    //如果数组内的元素大于1并且第一个元素的值相等
    if ([components count] > 1 && [(NSString *)[components objectAtIndex:0]isEqualToString:@"gallery"]) {
        if([(NSString *)[components objectAtIndex:1] isEqualToString:@"open"])
        {
            //[self openGallery];
        }
        return NO;
    }
    return YES;
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    //JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    if (webView.isLoading) {
        //return;
    }
    NSLog(@"webViewDidFinishLoad");
    //网页加载完成调用此方法
    if(![hud isHidden])
        [hud hide:YES];
    if(webView.canGoBack)
        menuView.previousBtn.highlighted=true;
       // ((UIImageView*)(((UIBarButtonItem*)bottomView.items[0]).customView)).highlighted=true;
    else
        menuView.previousBtn.highlighted=false;
        //((UIImageView*)(((UIBarButtonItem*)bottomView.items[0]).customView)).highlighted=false;
    if(webView.canGoForward){
        menuView.nextBtn.highlighted=true;
        //((UIImageView*)(((UIBarButtonItem*)bottomView.items[2]).customView)).highlighted=true;
        NSLog(@"forward-selected");
    }else{
        menuView.nextBtn.highlighted=false;
       // ((UIImageView*)(((UIBarButtonItem*)bottomView.items[2]).customView)).highlighted=false;
        NSLog(@"forward-normal");
    }
    //isReload=true;
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    NSLog(@"didFailLoadWithError==%ld",error.code);

    //网页加载失败 调用此方法
    if (webView.isLoading) {
        return;
    }else if(isReload){
        isReload=false;
        [self performSelector:@selector(refresh) withObject:nil afterDelay:0.3f];
        //[self refresh];
        return;
    }
    //NSLog(@"webViewDidFinishLoad");
    [self loadFailure];
}

-(void) loadFailure{
    if(!errorView){
        errorView=[[LoadFailureView alloc] initWithFrame:self.view.frame];
    }
    errorView.errorIv.image=[UIImage imageNamed:@"error_net.jpg"];
    errorView.errorLb.text=@"网络错误";
    errorView.reloadBtn.hidden=NO;
    [errorView.reloadBtn addTarget:self action:@selector(reloadData) forControlEvents:UIControlEventTouchUpInside];
    [webView addSubview:errorView];
}

-(void) reloadData{
    //NSLog(@"reloaddata");
    [errorView removeFromSuperview];
    [webView reload];
}
- (void)hudWasHidden:(MBProgressHUD *)h{
  //  NSLog(@"hudWasHidden");
    // Remove HUD from screen when the HUD was hidded
    [hud removeFromSuperview];
    //[hud release];
    hud = nil;
}

- (IBAction)menu{
   // NSLog(@"----menu");
    if(isShow)
        menuView.hidden=YES;
    else
        menuView.hidden=NO;
    isShow=!isShow;
}
@end
